package  {
	import starling.display.Sprite;
	import starling.display.MovieClip;
	import starling.events.Event;
	//import fl.transitions.Tween;
	//import fl.transitions.easing.*;
	//import fl.transitions.TweenEvent;
	
	public class ScreenHandler extends Sprite{
		private var _playscreen:PlayScreen;
		private var _seasonSelect:SeasonSelectScreen;
		private var _levelSelect:LevelSelect;
		private var _game:Game;
		
		private var newScreenName:String = "";
		
		private var screenLayer:Sprite = new Sprite();
		private var transitionLayer:Sprite = new Sprite();
		private var transition:Transition;
		private var transTimer:Number = 0;
		private var makeTransition:Boolean;
		
		public function ScreenHandler() {
			this.addChild(screenLayer);
			this.addChild(transitionLayer);
			_playscreen = new PlayScreen();
			screenLayer.addChild(_playscreen);
		}
		
		public function switchTo(screenName:String, trans:Boolean = true):void{
			newScreenName = screenName;
			makeTransition = trans;
			this.addEventListener(Event.ENTER_FRAME, switchScreens);
		}
		
		private function switchScreens(e:Event):void{
			if(makeTransition){
				transTimer++;
				if(transTimer == 1 && transitionLayer.numChildren < 1){
					transition = new Transition();
					transitionLayer.addChild(transition);
				}
				if(transTimer == transition.exitFrames){
					removeOldScreen();
					makeNewScreen();
					transTimer = 0;
					this.removeEventListener(Event.ENTER_FRAME, switchScreens);
				}
			} else {
				removeOldScreen();
				makeNewScreen();
				this.removeEventListener(Event.ENTER_FRAME, switchScreens);
			}
		}
		
		private function removeOldScreen():void{
			var oldScreen:MovieClip;
			oldScreen = screenLayer.getChildAt(0) as MovieClip;
			screenLayer.removeChild(oldScreen);
		}
		
		private function makeNewScreen():void{
			switch(newScreenName){
				case "PlayScreen":
					_playscreen = new "PlayScreen"();
					screenLayer.addChild(_playscreen);
					break;
				case "SeasonSelect":
					_seasonSelect = new SeasonSelectScreen();
					screenLayer.addChild(_seasonSelect);
					break;
				case "LevelSelect":
					_levelSelect = new LevelSelect();
					screenLayer.addChild(_levelSelect);
					break;
				case "Game":
					_game = new Game();
					screenLayer.addChild(_game);
					break;
				default:
				_playscreen = new "PlayScreen"();
				screenLayer.addChild(_playscreen);
				break;
			}
			newScreenName = "";
		}
	}
}